package cc.ug_project.rollcall.Fragments

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cc.ug_project.rollcall.Bussness.DataProviders.UserDataProvider
import cc.ug_project.rollcall.Dialogs.AddUserDialog
import cc.ug_project.rollcall.R
import com.ug_project.adapters.createRecyclerAdapter
import com.ug_project.alert.alert
import com.ug_project.objects.toArrayList
import com.ug_project.views.click
import com.ug_project.views.findTextView
import kotlinx.android.synthetic.main.fragment_user_manage.*


class UserManageFragment : Fragment() {
    val userDataProvider by lazy { UserDataProvider() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_user_manage, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        MemberList.layoutManager = LinearLayoutManager(context)
        loadData()

        AddActionButton.click {
            AddUserDialog(context, userDataProvider, { objectId, Exception ->
                if (Exception == null) {
                    alert(getString(R.string.success))
                    loadData()
                }
                else
                    alert(getString(R.string.failed))
            }).show()
        }
    }

    fun loadData(){
        userDataProvider.getAllUser { objects, exception ->
            if (exception != null){
                alert(context.getString(R.string.failed))
                return@getAllUser
            }

            MemberList.adapter = createRecyclerAdapter(context, R.layout.list_item_contacts, objects!!.toArrayList()){
                OnBindViewHolderIData { rootView, itemViewResID, data, position ->
                    rootView.findTextView(R.id.Name).text = data.name
                    rootView.findTextView(R.id.Tell).text = data.tellNumber
                }
            }
        }
    }
}